package com.ruoyi.backend.TypeHandlers;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.backend.pojo.RegulatoryTime;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class RegulatoryTimeListTypeHandler extends BaseTypeHandler<RegulatoryTime[]> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 该方法将 RegulatoryTime[] 数组转换为 JSON 字符串，并设置到 SQL 语句的指定参数位置。
     * 若序列化失败，则抛出 SQL 异常。
     * @param ps
     * @param i
     * @param parameter
     * @param jdbcType
     * @throws SQLException
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, RegulatoryTime[] parameter, JdbcType jdbcType) throws SQLException {
        try {
            String json = objectMapper.writeValueAsString(parameter);
            ps.setString(i, json);
        } catch (JsonProcessingException e) {
            throw new SQLException("Failed to serialize RegulatoryTime[] to JSON", e);
        }
    }

    @Override
    public RegulatoryTime[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String json = rs.getString(columnName);
        return parseJsonToRegulatoryTimeArray(json);
    }

    @Override
    public RegulatoryTime[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String json = rs.getString(columnIndex);
        return parseJsonToRegulatoryTimeArray(json);
    }

    @Override
    public RegulatoryTime[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String json = cs.getString(columnIndex);
        return parseJsonToRegulatoryTimeArray(json);
    }

    private RegulatoryTime[] parseJsonToRegulatoryTimeArray(String json) {
        if (json == null || json.isEmpty()) return new RegulatoryTime[0];
        try {
            return objectMapper.readValue(json, RegulatoryTime[].class);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Failed to deserialize JSON to RegulatoryTime[]", e);
        }
    }
}
